#!/bin/sh -x
## here is the main program
#sampleFile=$1
#amaConfig=$2
#maxEvt=$3
#amaFlags=$4

amaArgs=$@

retcode=0

source ama_util.sh

################################################
# resolving and setting TMPDIR env. variable
resolve_tmpdir

################################################
# setting glite UI environment 
set_glite_ui

################################################
# setting/checking the voms proxy
check_voms_proxy

################################################
# printtig basic WN information
print_wn_info

################################################
# get some machine infos
DATE=`date +'%D %T'`
MACH=`uname -srm`
MHZ=`cat /proc/cpuinfo | grep -i 'cpu mhz' | tail -1 | cut -d':' -f2 | tr -s ' ' `
MODEL=`cat /proc/cpuinfo | grep -i 'model name' | tail -1 | cut -d':' -f2 | tr -s ' '`
CACHE=`cat /proc/cpuinfo | grep -i 'cache size' | tail -1 | cut -d':' -f2 | tr -s ' '`
MEMORY=`cat /proc/meminfo | grep -i memtotal | cut -d':' -f2 | tr -s ' '`
HNAME=`hostname -f`
echo "### node info:   $DATE , $MHZ , $MODEL , $MEMORY , $CACHE , $MACH , $HNAME"

################################################
# detect ATLAS software
if [ -z $AMAUSER_PLATFORM ]; then
    echo "Platform type not defined." 1>&2
    exit 410103
fi

if [ n$AMAUSER_PLATFORM = n'grid' ]; then
    if [ -z $VO_ATLAS_SW_DIR ]; then
       echo "No ATLAS Software found." 1>&2
       # step exits with an error
       # WRAPLCG_WNCHEKC_SWENV
       exit 410103
    fi
fi

if [ n$AMAUSER_PLATFORM = n'local' ]; then
    if [ -z $ATLAS_SOFTWARE ]; then
       echo "No ATLAS Software found." 1>&2
       # step exits with an error
       # WRAPLCG_WNCHEKC_SWENV
       exit 410103
    fi
fi

################################################
# setup CMT 
cmt_setup

################################################
# fix g2c/gcc issues against SLC5

if [ n$CMTCONFIG != n'i686-slc5-gcc43-opt' ] && [ n$AMAUSER_PLATFORM = n'grid' ]; then

    fix_gcc_issue_sl5
fi

if [ n$AMAUSER_PLATFORM = n'local' ]; then
    fix_gcc_issue_sl5_local
fi

g++ --version
gcc --version

################################################
# setup AMA 
ama_setup

if [ $? -ne 0 ]; then
    echo "AMA setup failed" 1>&2
    exit 410104
fi

################################################
# run AMA 
ama_run $amaArgs

if [ $? -ne 0 ]; then
    echo "AMA runtime error" 1>&2
    exit 410106
fi
